import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { ModelSchema } from '../entities/model-schema.entity'
import { FieldDefinition } from '../entities/field-definition.entity'
import { TableGeneratorService } from './table-generator.service'

/**
 * 元数据服务
 * 提供模型注册、查询等核心逻辑
 */
@Injectable()
export class MetadataService {
  constructor(
    @InjectRepository(ModelSchema)
    private readonly modelRepo: Repository<ModelSchema>,
    @InjectRepository(FieldDefinition)
    private readonly fieldRepo: Repository<FieldDefinition>,
    private readonly tableGeneratorService: TableGeneratorService,
  ) {}

  /**
   * 注册新模型
   * @param modelData { name, label, fields }
   */
  async registerModel(modelData: {
    name: string
    label: string
    fields: Array<{
      name: string
      type: string
      label?: string
      required?: boolean
    }>
  }): Promise<ModelSchema> {
    // 检查模型名唯一性
    const exist = await this.modelRepo.findOne({ where: { name: modelData.name } })
    if (exist) throw new Error(`模型名 ${modelData.name} 已存在`)

    // 创建模型实体
    const model = this.modelRepo.create({
      name: modelData.name,
      label: modelData.label,
    })
    await this.modelRepo.save(model)

    // 创建字段实体
    const fields = modelData.fields.map((f) => this.fieldRepo.create({ ...f, model }))
    await this.fieldRepo.save(fields)

    // 自动建表（动态表结构生成）
    await this.tableGeneratorService.createTableForModel({ ...model, fields })

    // 返回完整模型（含字段）
    return this.modelRepo.findOne({ where: { id: model.id }, relations: ['fields'] }) as Promise<ModelSchema>
  }

  /**
   * 获取所有模型列表
   */
  async getAllModels(): Promise<ModelSchema[]> {
    return this.modelRepo.find({ relations: ['fields'] })
  }

  /**
   * 获取指定模型详情
   * @param name 模型名
   */
  async getModel(name: string): Promise<ModelSchema | undefined> {
    const model = await this.modelRepo.findOne({ where: { name }, relations: ['fields'] })
    return model ?? undefined
  }
}
